package com.liqin.nothing.main;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author gonghl
 */
public class SemaphoreExample {

    // 共享资源的限制数量
    private static final int RESOURCE_LIMIT = 5;
    private static final Semaphore SEMAPHORE = new Semaphore(RESOURCE_LIMIT);

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new ResourceConsumer()).start();
        }
    }

    static class ResourceConsumer implements Runnable {
        @Override
        public void run() {
            try {
                // 请求一个许可
                SEMAPHORE.acquire();

                System.out.println("线程 " + Thread.currentThread().getName() + " 开始访问资源");
                // 模拟资源访问
                TimeUnit.SECONDS.sleep(2);
                System.out.println("线程 " + Thread.currentThread().getName() + " 结束访问资源");

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                // 释放一个许可
                SEMAPHORE.release();
            }
        }
    }
}
